<template>
    <!-- 巡检点位设置 -->
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="auto">
            <!-- <el-form-item label="id" prop="inspectionId">
                <el-input v-model="queryParams.inspectionId" placeholder="请输入id" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item> -->
            <el-form-item label="站点名称" prop="groupId">
                <el-select v-model="queryParams.groupId" style="width: 100%;" placeholder="请选择站点">
                    <el-option v-for="dict in groupData" :key="dict.siteId" :label="dict.groupName"
                        :value="dict.groupId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="巡检名称" prop="inspectioName">
                <el-input v-model="queryParams.inspectioName" placeholder="请输入巡检名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>


        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['his:barrel:add']">新增</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['his:barrel:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['his:barrel:remove']">删除</el-button>
            </el-col> -->
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="downLoadQrcode"
                    v-hasPermi="['his:medicine:export']">下载二维码</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="barrelList">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="id" align="center" prop="inspectionId" /> -->
            <el-table-column label="站点名称" align="center" prop="groupName" />
            <el-table-column label="巡检名称" align="center" prop="inspectionName" />
            <el-table-column label="巡检内容" align="center" prop="inspectionContent" />
            <el-table-column label="关联设备" align="center" prop="deviceType">
                <template slot-scope="scope">
                    <div>{{ nDeviceFun(scope.row.deviceType) }}</div>
                </template>
            </el-table-column>
            <el-table-column label="二维码" align="center" prop=" " width="140">
                <template slot-scope="scope">
                    <!-- <div id="qrcodeArea"
                        style="transform: scale(0.3,0.3);width: 100px;height: 120px;padding: 0;margin: 0 ;display: flex;">
                        <qrcode style="margin-top: -100px;" :ref="scope.row.id" :qrid="scope.row.id"
                            :qrContent="scope.row.id" :qrTitle="scope.row.title" qrHeight="300" qrWidth="300"
                            @imgSrcFun="imgSrcDataFun($event, scope.row)" />
                    </div> -->
                    <div style="color: blue;cursor: pointer;" @click="qrCodeFun(scope.row)">
                        查看二维码
                    </div>
                </template>
            </el-table-column>
            <!-- <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.associated_devices" :value="scope.row.status" />
                </template>
            </el-table-column> -->
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['his:barrel:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['his:barrel:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改药桶编号对话框 -->
        <!-- 添加或修改巡检设置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="35%" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="auto">
                <!-- <el-form-item label="id" prop="inspectionId">
                    <el-input v-model="form.inspectionId" placeholder="请输入id" />
                </el-form-item> -->
                <el-form-item label="站点" prop="groupId">
                    <el-select v-model="form.groupId" @change="groupChange" style="width: 100%;" placeholder="请选择站点">
                        <el-option v-for="dict in groupData" :key="dict.siteId" :label="dict.groupName"
                            :value="dict.groupId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="巡检名称" prop="inspectionName">
                    <el-input v-model="form.inspectionName" placeholder="请输入巡检名称" />
                </el-form-item>
                <el-form-item label="巡检内容" prop="inspectionContent">
                    <!-- <editor v-model="form.inspectioContent" :min-height="192" /> -->
                    <el-input v-model="form.inspectionContent" type="textarea" placeholder="请输入巡检内容" />
                </el-form-item>
                <el-form-item label="关联设备" prop="deviceType">
                    <el-select v-model="form.deviceType" style="width: 100%;" placeholder="请选择关联设备">
                        <el-option v-for="dict in listInspectionDeviceData" :key="dict.id"
                            :label="dict.inspectionDeviceName" :value="dict.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="扩展字段" prop="extendData">
                    <el-input v-model="form.extendData" placeholder="请输入内容" />
                </el-form-item> -->
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 添加或修改药桶编号对话框 -->
        <el-dialog title="二维码" :visible.sync="qrcodePpen" width="600px" destroy-on-close>
            <div style="display: flex;justify-content: center;align-items: center;">
                <qrcodeimg :qrid="qrcodeItem.inspectionSettingId" :qrTitle="qrcodeItem.inspectionDeviceName"
                    :qrContent="qrcodeItem.inspectionSettingId" qrHeight="300" qrWidth="300" />
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="qrcodePpen = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listSetting, getSetting, delSetting, addSetting, updateSetting } from "@/api/site/set";
import { listGroup } from '@/api/iot/group'
import { listInspectionDevice } from "@/api/iot/InspectionDevice";

// 引入依赖
import JSZip from 'jszip'
import FileSaver from "file-saver";


export default {
    name: "Set",
    dicts: ['sys_normal_disable', 'his_medicine_type', 'associated_devices'],
    data() {
        return {
            qrcodeItem: {},
            qrcodePpen: false,
            pageSizes: [6, 10, 20, 30, 50],
            qrWidth: 70,
            qrHeight: 70,
            qrContent: "",
            barrelList: [],
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 巡检设置表格数据
            setList: [],
            setAllList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                inspectionId: null,
                siteId: null,
                inspectioName: null,
                inspectioContent: null,
                deviceId: null,
                status: null,
                groupId: null,
            },
            // 表单参数
            form: {
                deviceId: []
            },
            // 表单校验
            rules: {
                groupId: [
                    { required: true, message: "站点不能为空", trigger: "blur" }
                ],
                inspectionName: [
                    { required: true, message: "巡检名称不能为空", trigger: "blur" }
                ],
                inspectionContent: [
                    { required: true, message: "巡检内容不能为空", trigger: "blur" }
                ],
                deviceType: [
                    { required: true, message: "关联设备不能为空", trigger: "blur" }
                ],
            },
            allListSetData: [],
            allListDeviceData: [],
            groupData: [],
            listInspectionDeviceData: [],
        };
    },
    created() {
        this.getList();
        this.listGroupFun();
        this.listInspectionDeviceFun();
    },
    methods: {

        listInspectionDeviceFun() {
            listInspectionDevice({
                pageNum: 1,
                pageSize: 100,
            }).then(res => {
                this.listInspectionDeviceData = res.rows;
            })
        },
        nDeviceFun(val) {
            if (!val) {
                return
            }
            for (let item of this.listInspectionDeviceData) {
                if (item.id == val) {
                    return item.inspectionDeviceName
                }
            }
        },
        groupChange(e) {

            for (let item of this.groupData) {
                if (item.groupId == e) {
                    this.form.groupName = item.groupName
                }
            }

        },
        listGroupFun() {
            let params = {
                pageSize: 999,
                pageNum: 1,
            }
            listGroup(params).then((res) => {
                let groupList = res.rows;
                this.groupData = groupList;
            })
        },
        getQRCodeUrl(qrcode_url, id) {
            // 此处是一个坑，
            this.$refs['qrcodeBox' + id].innerHTML = '';
            new QRCode(this.$refs['qrcodeBox' + id], {
                text: qrcode_url, // 需要转换为二维码的内容
                width: 60,
                height: 60,
                // render: "canvas", // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
                colorDark: '#000000', //二维码颜色
                colorLight: '#ffffff', //二维码背景色
                correctLevel: QRCode.CorrectLevel.H //容错率，L/M/H
            });
        },
        imgSrcDataFun(data, item) {
            for (let res of this.barrelList) {
                if (res.id == item.id) {
                    item['imgUrlQrcode'] = data
                }
            }
        },
        // 下载二维码
        downLoadQrcode() {
            const zip = new JSZip() // 创建一个zip实例
            for (const key in this.barrelList) {
                const item = this.barrelList[key]
                // 把生成的二维码文件添加到zip中
                zip.file(`${item.title}.png`, this.dataURLToBlob(item.imgUrlQrcode), { binary: true })
            }
            Promise.all(this.barrelList).then(res => {
                // 打包文件
                zip.generateAsync({ type: 'blob' }).then(content => {
                    // 下载zip文件
                    FileSaver.saveAs(content, "药桶编号.zip")
                })
            })
        },
        dataURLToBlob(cropperData) {
            let arr = cropperData.split(",");
            let mime = arr[0].match(/:(.*?);/)[1];
            let bstr = atob(arr[1]);
            let n = bstr.length;
            let u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        },


        /** 查询巡检设置列表 */
        getList() {
            this.loading = true;
            listSetting(this.queryParams).then(response => {
                this.barrelList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },


        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                inspectionId: null,
                siteId: null,
                inspectioName: null,
                inspectioContent: null,
                deviceId: null,
                extendData: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                status: null,
                delFlag: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.inspectionSettingId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加巡检设置";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const inspectionId = row.inspectionSettingId || this.ids
            getSetting(inspectionId).then(response => {
                this.form = response.data;
                this.form.deviceType = this.form.deviceType * 1;
                this.open = true;
                this.title = "修改巡检设置";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.inspectionSettingId != null) {
                        updateSetting(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addSetting(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const inspectionIds = row.inspectionSettingId || this.ids;
            this.$modal.confirm('是否确认删除巡检设置编号为"' + inspectionIds + '"的数据项？').then(function () {
                return delSetting(inspectionIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('site/set/export', {
                ...this.queryParams
            }, `set_${new Date().getTime()}.xlsx`)
        },

        qrCodeFun(item) {
            this.qrcodeItem = item

            this.qrcodePpen = true

        }
    }
};
</script>
